// pages/Connections/ConnectionList.tsx
import React, { useEffect, useState } from 'react';
import type { ConnectionDetail } from '../../types/api';
import { useNavigate } from 'react-router-dom';
import { Link, Plus, RefreshCw, Trash2, Power, PowerOff, Settings, CheckCircle, AlertCircle } from 'lucide-react';
import { useConnectionStore } from '../../stores/connectionStore';
import { useApp } from '../../App';
import { ROUTES } from '../../router';

const ConnectionList: React.FC = () => {
  const navigate = useNavigate();
  const { currentConnection, setCurrentConnection } = useApp();
  const {
    connections,
    loading,
    error,
    fetchConnections,
    deleteConnection,
    reconnectConnection,
    closeConnection,
    setDefaultConnection,
    checkConnectionHealth
  } = useConnectionStore();

  const [healthStatus, setHealthStatus] = useState<Record<string, boolean>>({});

  useEffect(() => {
    fetchConnections();
  }, []);

  // ��ޥe��
  useEffect(() => {
    const checkHealth = async () => {
      const status: Record<string, boolean> = {};
      for (const conn of connections) {
        try {
          const result = await checkConnectionHealth(conn.name);
          status[conn.name] = result.message === 'healthy';
        } catch {
          status[conn.name] = false;
        }
      }
      setHealthStatus(status);
    };

    if (connections.length > 0) {
      checkHealth();
    }
  }, [connections]);

  const handleDeleteConnection = async (connectionName: string) => {
    if (window.confirm(`Are you sure you want to delete connection "${connectionName}"?`)) {
      try {
        await deleteConnection(connectionName);
      } catch (error) {
        console.error('Failed to delete connection:', error);
      }
    }
  };

  const handleReconnectConnection = async (connectionName: string) => {
    try {
      await reconnectConnection(connectionName);
    } catch (error) {
      console.error('Failed to reconnect:', error);
    }
  };

  const handleCloseConnection = async (connectionName: string) => {
    try {
      await closeConnection(connectionName);
    } catch (error) {
      console.error('Failed to close connection:', error);
    }
  };

  const handleSetDefaultConnection = async (connectionName: string) => {
    try {
      await setDefaultConnection(connectionName);
    } catch (error) {
      console.error('Failed to set default connection:', error);
    }
  };

  const handleSelectConnection = (connectionName: string) => {
    setCurrentConnection(connectionName);
  };

  const getConnectionStatus = (connection: ConnectionDetail) => {
    const isHealthy = healthStatus[connection.name];
    if (connection.connected && isHealthy) {
      return { color: 'text-green-500', label: 'Connected' };
    } else if (connection.connected) {
      return { color: 'text-yellow-500', label: 'Unhealthy' };
    } else {
      return { color: 'text-red-500', label: 'Disconnected' };
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-8">
        <p className="text-red-500 mb-4">{error}</p>
        <button
          onClick={fetchConnections}
          className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Connections</h2>
        <div className="flex gap-2">
          <button
            onClick={fetchConnections}
            className="flex items-center gap-2 px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors"
          >
            <RefreshCw size={16} />
            Refresh
          </button>
          <button
            onClick={() => navigate(ROUTES.CONNECTION_NEW)}
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
          >
            <Plus size={16} />
            New Connection
          </button>
        </div>
      </div>

      {connections.length === 0 ? (
        <div className="text-center py-12">
          <Link className="mx-auto mb-4 text-gray-400" size={48} />
          <p className="text-lg text-gray-400 mb-4">No connections found</p>
          <button
            onClick={() => navigate(ROUTES.CONNECTION_NEW)}
            className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
          >
            Create Connection
          </button>
        </div>
      ) : (
        <div className="grid gap-4">
          {connections.map((connection) => {
            const status = getConnectionStatus(connection);
            const isCurrent = currentConnection === connection.name;
            const isDefault = connection.name === 'default';

            return (
              <div
                key={connection.name}
                className={`p-4 rounded-lg border transition-all ${
                  isCurrent
                    ? 'border-purple-500 bg-purple-500/10'
                    : 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900'
                }`}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="flex items-center gap-2">
                      {status.color === 'text-green-500' ? (
                        <CheckCircle className={`${status.color}`} size={20} />
                      ) : (
                        <AlertCircle className={`${status.color}`} size={20} />
                      )}
                      <div>
                        <h3 className="font-semibold">{connection.name}</h3>
                        <p className="text-sm text-gray-500">{connection.uri}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className={`text-sm ${status.color}`}>{status.label}</span>
                      {isDefault && (
                        <span className="px-2 py-1 text-xs bg-blue-500 text-white rounded">Default</span>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    {!isCurrent && (
                      <button
                        onClick={() => handleSelectConnection(connection.name)}
                        className="px-3 py-1 text-sm bg-purple-600 hover:bg-purple-700 text-white rounded transition-colors"
                      >
                        Select
                      </button>
                    )}

                    {connection.connected ? (
                      <>
                        <button
                          onClick={() => handleCloseConnection(connection.name)}
                          className="p-2 text-red-500 hover:bg-red-500/10 rounded transition-colors"
                          title="Close Connection"
                        >
                          <PowerOff size={16} />
                        </button>
                        <button
                          onClick={() => handleReconnectConnection(connection.name)}
                          className="p-2 text-blue-500 hover:bg-blue-500/10 rounded transition-colors"
                          title="Reconnect"
                        >
                          <RefreshCw size={16} />
                        </button>
                      </>
                    ) : (
                      <button
                        onClick={() => handleReconnectConnection(connection.name)}
                        className="p-2 text-green-500 hover:bg-green-500/10 rounded transition-colors"
                        title="Connect"
                      >
                        <Power size={16} />
                      </button>
                    )}

                    {!isDefault && (
                      <button
                        onClick={() => handleSetDefaultConnection(connection.name)}
                        className="p-2 text-yellow-500 hover:bg-yellow-500/10 rounded transition-colors"
                        title="Set as Default"
                      >
                        <Settings size={16} />
                      </button>
                    )}

                    <button
                      onClick={() => handleDeleteConnection(connection.name)}
                      className="p-2 text-red-500 hover:bg-red-500/10 rounded transition-colors"
                      title="Delete Connection"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default ConnectionList;